package com.cf.limit.core.filter;

import com.cf.constant.EnumReturnCode;
import com.cf.limit.core.service.BlackService;
import com.cf.util.RequestUtil;
import com.cf.vo.ResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * game-server-BlackFilter
 *
 * @author <a href="2428922347@qq.com">Zhu mingming</a>
 * @info
 * @since 2018/6/15 下午 05:35
 */
@Slf4j
@Order(-20)
@WebFilter(displayName = "blackFilter", filterName = "blackFilter")
public class BlackFilter implements Filter {

    @Autowired
    private BlackService blackService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("黑名单过滤器初始化。。。。");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String ip = RequestUtil.getIpAddr((HttpServletRequest) request);

        boolean black = blackService.isBlack(ip);
        if (black) {
            log.info("ip【{}】为黑名单用户，拒绝访问。。。。。");
            RequestUtil.renderJson((HttpServletResponse) response, ResponseVo.fail(EnumReturnCode.ERROR.getCode(), null, "访问过于频繁！"));
            return;
        }
        log.info("ip【{}】为普通用户，允许访问。。。。。",RequestUtil.getIpAddr((HttpServletRequest) request));
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {

    }
}
